home *** CD-ROM | disk | FTP | other *** search
/ Nebula 1 / Nebula One.iso / Misc / msql-1.0.6 / src / regexp / regexp.c < prev    next >
C/C++ Source or Header  |  1994-08-18  |  28KB  |  1,227 lines

  1. /*
  2.  * regcomp and regexec -- regsub and regerror are elsewhere
  3.  * @(#)regexp.c    1.3 of 18 April 87
  4.  *
  5.  *    Copyright (c) 1986 by University of Toronto.
  6.  *    Written by Henry Spencer.  Not derived from licensed software.
  7.  *
  8.  *    Permission is granted to anyone to use this software for any
  9.  *    purpose on any computer system, and to redistribute it freely,
  10.  *    subject to the following restrictions:
  11.  *
  12.  *    1. The author is not responsible for the consequences of use of
  13.  *        this software, no matter how awful, even if they arise
  14.  *        from defects in it.
  15.  *
  16.  *    2. The origin of this software must not be misrepresented, either
  17.  *        by explicit claim or by omission.
  18.  *
  19.  *    3. Altered versions must be plainly marked as such, and must not
  20.  *        be misrepresented as being the original software.
  21.  *
  22.  * Beware that some of this code is subtly aware of the way operator
  23.  * precedence is structured in regular expressions.  Serious changes in
  24.  * regular-expression syntax might require a total rethink.
  25.  */
  26. #include <stdio.h>
  27. #include <regexp.h>
  28.  
  29. #include <common/portability.h>
  30.  
  31.  
  32. #include "regmagic.h"
  33.  
  34. /*
  35.  * The "internal use only" fields in regexp.h are present to pass info from
  36.  * compile to execute that permits the execute phase to run lots faster on
  37.  * simple cases.  They are:
  38.  *
  39.  * regstart    char that must begin a match; '\0' if none obvious
  40.  * reganch    is the match anchored (at beginning-of-line only)?
  41.  * regmust    string (pointer into program) that match must include, or NULL
  42.  * regmlen    length of regmust string
  43.  *
  44.  * Regstart and reganch permit very fast decisions on suitable starting points
  45.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  46.  * of lines that cannot possibly match.  The regmust tests are costly enough
  47.  * that regcomp() supplies a regmust only if the r.e. contains something
  48.  * potentially expensive (at present, the only such thing detected is * or +
  49.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  50.  * supplied because the test in regexec() needs it and regcomp() is computing
  51.  * it anyway.
  52.  */
  53.  
  54. /*
  55.  * Structure for regexp "program".  This is essentially a linear encoding
  56.  * of a nondeterministic finite-state machine (aka syntax charts or
  57.  * "railroad normal form" in parsing technology).  Each node is an opcode
  58.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  59.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  60.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  61.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  62.  * opposed to a collection of them) is never concatenated with anything
  63.  * because of operator precedence.)  The operand of some types of node is
  64.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  65.  * particular, the operand of a BRANCH node is the first node of the branch.
  66.  * (NB this is *not* a tree structure:  the tail of the branch connects
  67.  * to the thing following the set of BRANCHes.)  The opcodes are:
  68.  */
  69.  
  70. /* definition    number    opnd?    meaning */
  71. #define    END    0    /* no    End of program. */
  72. #define    BOL    1    /* no    Match "" at beginning of line. */
  73. #define    EOL    2    /* no    Match "" at end of line. */
  74. #define    ANY    3    /* no    Match any one character. */
  75. #define    ANYOF    4    /* str    Match any character in this string. */
  76. #define    ANYBUT    5    /* str    Match any character not in this string. */
  77. #define    BRANCH    6    /* node    Match this alternative, or the next... */
  78. #define    BACK    7    /* no    Match "", "next" ptr points backward. */
  79. #define    EXACTLY    8    /* str    Match this string. */
  80. #define    NOTHING    9    /* no    Match empty string. */
  81. #define    STAR    10    /* node    Match this (simple) thing 0 or more times. */
  82. #define    PLUS    11    /* node    Match this (simple) thing 1 or more times. */
  83. #define    OPEN    20    /* no    Mark this point in input as start of #n. */
  84.             /*    OPEN+1 is number 1, etc. */
  85. #define    CLOSE    30    /* no    Analogous to OPEN. */
  86.  
  87. /*
  88.  * Opcode notes:
  89.  *
  90.  * BRANCH    The set of branches constituting a single choice are hooked
  91.  *        together with their "next" pointers, since precedence prevents
  92.  *        anything being concatenated to any individual branch.  The
  93.  *        "next" pointer of the last BRANCH in a choice points to the
  94.  *        thing following the whole choice.  This is also where the
  95.  *        final "next" pointer of each individual branch points; each
  96.  *        branch starts with the operand node of a BRANCH node.
  97.  *
  98.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  99.  *        exists to make loop structures possible.
  100.  *
  101.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  102.  *        BRANCH structures using BACK.  Simple cases (one character
  103.  *        per match) are implemented with STAR and PLUS for speed
  104.  *        and to minimize recursive plunges.
  105.  *
  106.  * OPEN,CLOSE    ...are numbered at compile time.
  107.  */
  108.  
  109. /*
  110.  * A node is one char of opcode followed by two chars of "next" pointer.
  111.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  112.  * value is a positive offset from the opcode of the node containing it.
  113.  * An operand, if any, simply follows the node.  (Note that much of the
  114.  * code generation knows about this implicit relationship.)
  115.  *
  116.  * Using two bytes for the "next" pointer is vast overkill for most things,
  117.  * but allows patterns to get big without disasters.
  118.  */
  119. #define    OP(p)    (*(p))
  120. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  121. #define    OPERAND(p)    ((p) + 3)
  122.  
  123. /*
  124.  * See regmagic.h for one further detail of program structure.
  125.  */
  126.  
  127.  
  128. /*
  129.  * Utility definitions.
  130.  */
  131. #ifndef CHARBITS
  132. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  133. #else
  134. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  135. #endif
  136.  
  137. #define    FAIL(m)    { regerror(m); return(NULL); }
  138. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  139. #define    META    "^$.[()|?+*\\"
  140.  
  141. /*
  142.  * Flags to be passed up and down.
  143.  */
  144. #define    HASWIDTH    01    /* Known never to match null string. */
  145. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  146. #define    SPSTART        04    /* Starts with * or +. */
  147. #define    WORST        0    /* Worst case. */
  148.  
  149. /*
  150.  * Global work variables for regcomp().
  151.  */
  152. static char *regparse;        /* Input-scan pointer. */
  153. static int regnpar;        /* () count. */
  154. static char regdummy;
  155. static char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  156. static long regsize;        /* Code size. */
  157.  
  158. /*
  159.  * Forward declarations for regcomp()'s friends.
  160.  */
  161. #ifndef STATIC
  162. #define    STATIC    static
  163. #endif
  164. STATIC char *reg();
  165. STATIC char *regbranch();
  166. STATIC char *regpiece();
  167. STATIC char *regatom();
  168. STATIC char *regnode();
  169. STATIC char *regnext();
  170. STATIC void regc();
  171. STATIC void reginsert();
  172. STATIC void regtail();
  173. STATIC void regoptail();
  174. #ifdef STRCSPN
  175. STATIC int strcspn();
  176. #endif
  177.  
  178. /*
  179.  - regcomp - compile a regular expression into internal code
  180.  *
  181.  * We can't allocate space until we know how big the compiled form will be,
  182.  * but we can't compile it (and thus know how big it is) until we've got a
  183.  * place to put the code.  So we cheat:  we compile it twice, once with code
  184.  * generation turned off and size counting turned on, and once "for real".
  185.  * This also means that we don't allocate space until we are sure that the
  186.  * thing really will compile successfully, and we never have to move the
  187.  * code and thus invalidate pointers into it.  (Note that it has to be in
  188.  * one piece because free() must be able to free it all.)
  189.  *
  190.  * Beware that the optimization-preparation code in here knows about some
  191.  * of the structure of the compiled regexp.
  192.  */
  193.  
  194. /*
  195. ** It is bad kama to assume that a malloc'ed block has been zeroed.  It
  196. ** often isn't particularly under SunOS.  Kiss those NULL pointer checks
  197. ** good bye   -   bambi@Bond.edu.au  15/1/94
  198. */
  199.  
  200. regexp *
  201. regcomp(exp)
  202. char *exp;
  203. {
  204.     register regexp *r;
  205.     register char *scan;
  206.     register char *longest;
  207.     register int len;
  208.     int flags;
  209.     extern char *malloc();
  210.  
  211.     if (exp == NULL)
  212.         FAIL("NULL argument");
  213.  
  214.     /* First pass: determine size, legality. */
  215.     regparse = exp;
  216.     regnpar = 1;
  217.     regsize = 0L;
  218.     regcode = ®dummy;
  219.     regc(MAGIC);
  220.     if (reg(0, &flags) == NULL)
  221.         return(NULL);
  222.  
  223.     /* Small enough for pointer-storage convention? */
  224.     if (regsize >= 32767L)        /* Probably could be 65535L. */
  225.         FAIL("regexp too big");
  226.  
  227.     /* Allocate space. */
  228.     r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
  229.     if (r == NULL)
  230.         FAIL("out of space");
  231.     (void)bzero(r, sizeof(regexp) + (unsigned)regsize);  /* bambi */
  232.  
  233.     /* Second pass: emit code. */
  234.     regparse = exp;
  235.     regnpar = 1;
  236.     regcode = r->program;
  237.     regc(MAGIC);
  238.     if (reg(0, &flags) == NULL)
  239.         return(NULL);
  240.  
  241.     /* Dig out information for optimizations. */
  242.     r->regstart = '\0';    /* Worst-case defaults. */
  243.     r->reganch = 0;
  244.     r->regmust = NULL;
  245.     r->regmlen = 0;
  246.     scan = r->program+1;            /* First BRANCH. */
  247.     if (OP(regnext(scan)) == END) {        /* Only one top-level choice. */
  248.         scan = OPERAND(scan);
  249.  
  250.         /* Starting-point info. */
  251.         if (OP(scan) == EXACTLY)
  252.             r->regstart = *OPERAND(scan);
  253.         else if (OP(scan) == BOL)
  254.             r->reganch++;
  255.  
  256.         /*
  257.          * If there's something expensive in the r.e., find the
  258.          * longest literal string that must appear and make it the
  259.          * regmust.  Resolve ties in favor of later strings, since
  260.          * the regstart check works with the beginning of the r.e.
  261.          * and avoiding duplication strengthens checking.  Not a
  262.          * strong reason, but sufficient in the absence of others.
  263.          */
  264.         if (flags&SPSTART) {
  265.             longest = NULL;
  266.             len = 0;
  267.             for (; scan != NULL; scan = regnext(scan))
  268.                 if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  269.                     longest = OPERAND(scan);
  270.                     len = strlen(OPERAND(scan));
  271.                 }
  272.             r->regmust = longest;
  273.             r->regmlen = len;
  274.         }
  275.     }
  276.  
  277.     return(r);
  278. }
  279.  
  280. /*
  281.  - reg - regular expression, i.e. main body or parenthesized thing
  282.  *
  283.  * Caller must absorb opening parenthesis.
  284.  *
  285.  * Combining parenthesis handling with the base level of regular expression
  286.  * is a trifle forced, but the need to tie the tails of the branches to what
  287.  * follows makes it hard to avoid.
  288.  */
  289. static char *
  290. reg(paren, flagp)
  291. int paren;            /* Parenthesized? */
  292. int *flagp;
  293. {
  294.     register char *ret;
  295.     register char *br;
  296.     register char *ender;
  297.     register int parno;
  298.     int flags;
  299.  
  300.     *flagp = HASWIDTH;    /* Tentatively. */
  301.  
  302.     /* Make an OPEN node, if parenthesized. */
  303.     if (paren) {
  304.         if (regnpar >= NSUBEXP)
  305.             FAIL("too many ()");
  306.         parno = regnpar;
  307.         regnpar++;
  308.         ret = regnode(OPEN+parno);
  309.     } else
  310.         ret = NULL;
  311.  
  312.     /* Pick up the branches, linking them together. */
  313.     br = regbranch(&flags);
  314.     if (br == NULL)
  315.         return(NULL);
  316.     if (ret != NULL)
  317.         regtail(ret, br);    /* OPEN -> first. */
  318.     else
  319.         ret = br;
  320.     if (!(flags&HASWIDTH))
  321.         *flagp &= ~HASWIDTH;
  322.     *flagp |= flags&SPSTART;
  323.     while (*regparse == '|') {
  324.         regparse++;
  325.         br = regbranch(&flags);
  326.         if (br == NULL)
  327.             return(NULL);
  328.         regtail(ret, br);    /* BRANCH -> BRANCH. */
  329.         if (!(flags&HASWIDTH))
  330.             *flagp &= ~HASWIDTH;
  331.         *flagp |= flags&SPSTART;
  332.     }
  333.  
  334.     /* Make a closing node, and hook it on the end. */
  335.     ender = regnode((paren) ? CLOSE+parno : END);    
  336.     regtail(ret, ender);
  337.  
  338.     /* Hook the tails of the branches to the closing node. */
  339.     for (br = ret; br != NULL; br = regnext(br))
  340.         regoptail(br, ender);
  341.  
  342.     /* Check for proper termination. */
  343.     if (paren && *regparse++ != ')') {
  344.         FAIL("unmatched ()");
  345.     } else if (!paren && *regparse != '\0') {
  346.         if (*regparse == ')') {
  347.             FAIL("unmatched ()");
  348.         } else
  349.             FAIL("junk on end");    /* "Can't happen". */
  350.         /* NOTREACHED */
  351.     }
  352.  
  353.     return(ret);
  354. }
  355.  
  356. /*
  357.  - regbranch - one alternative of an | operator
  358.  *
  359.  * Implements the concatenation operator.
  360.  */
  361. static char *
  362. regbranch(flagp)
  363. int *flagp;
  364. {
  365.     register char *ret;
  366.     register char *chain;
  367.     register char *latest;
  368.     int flags;
  369.  
  370.     *flagp = WORST;        /* Tentatively. */
  371.  
  372.     ret = regnode(BRANCH);
  373.     chain = NULL;
  374.     while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  375.         latest = regpiece(&flags);
  376.         if (latest == NULL)
  377.             return(NULL);
  378.         *flagp |= flags&HASWIDTH;
  379.         if (chain == NULL)    /* First piece. */
  380.             *flagp |= flags&SPSTART;
  381.         else
  382.             regtail(chain, latest);
  383.         chain = latest;
  384.     }
  385.     if (chain == NULL)    /* Loop ran zero times. */
  386.         (void) regnode(NOTHING);
  387.  
  388.     return(ret);
  389. }
  390.  
  391. /*
  392.  - regpiece - something followed by possible [*+?]
  393.  *
  394.  * Note that the branching code sequences used for ? and the general cases
  395.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  396.  * both the endmarker for their branch list and the body of the last branch.
  397.  * It might seem that this node could be dispensed with entirely, but the
  398.  * endmarker role is not redundant.
  399.  */
  400. static char *
  401. regpiece(flagp)
  402. int *flagp;
  403. {
  404.     register char *ret;
  405.     register char op;
  406.     register char *next;
  407.     int flags;
  408.  
  409.     ret = regatom(&flags);
  410.     if (ret == NULL)
  411.         return(NULL);
  412.  
  413.     op = *regparse;
  414.     if (!ISMULT(op)) {
  415.         *flagp = flags;
  416.         return(ret);
  417.     }
  418.  
  419.     if (!(flags&HASWIDTH) && op != '?')
  420.         FAIL("*+ operand could be empty");
  421.     *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
  422.  
  423.     if (op == '*' && (flags&SIMPLE))
  424.         reginsert(STAR, ret);
  425.     else if (op == '*') {
  426.         /* Emit x* as (x&|), where & means "self". */
  427.         reginsert(BRANCH, ret);            /* Either x */
  428.         regoptail(ret, regnode(BACK));        /* and loop */
  429.         regoptail(ret, ret);            /* back */
  430.         regtail(ret, regnode(BRANCH));        /* or */
  431.         regtail(ret, regnode(NOTHING));        /* null. */
  432.     } else if (op == '+' && (flags&SIMPLE))
  433.         reginsert(PLUS, ret);
  434.     else if (op == '+') {
  435.         /* Emit x+ as x(&|), where & means "self". */
  436.         next = regnode(BRANCH);            /* Either */
  437.         regtail(ret, next);
  438.         regtail(regnode(BACK), ret);        /* loop back */
  439.         regtail(next, regnode(BRANCH));        /* or */
  440.         regtail(ret, regnode(NOTHING));        /* null. */
  441.     } else if (op == '?') {
  442.         /* Emit x? as (x|) */
  443.         reginsert(BRANCH, ret);            /* Either x */
  444.         regtail(ret, regnode(BRANCH));        /* or */
  445.         next = regnode(NOTHING);        /* null. */
  446.         regtail(ret, next);
  447.         regoptail(ret, next);
  448.     }
  449.     regparse++;
  450.     if (ISMULT(*regparse))
  451.         FAIL("nested *?+");
  452.  
  453.     return(ret);
  454. }
  455.  
  456. /*
  457.  - regatom - the lowest level
  458.  *
  459.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  460.  * it can turn them into a single node, which is smaller to store and
  461.  * faster to run.  Backslashed characters are exceptions, each becoming a
  462.  * separate node; the code is simpler that way and it's not worth fixing.
  463.  */
  464. static char *
  465. regatom(flagp)
  466. int *flagp;
  467. {
  468.     register char *ret;
  469.     int flags;
  470.  
  471.     *flagp = WORST;        /* Tentatively. */
  472.  
  473.     switch (*regparse++) {
  474.     case '^':
  475.         ret = regnode(BOL);
  476.         break;
  477.     case '$':
  478.         ret = regnode(EOL);
  479.         break;
  480.     case '.':
  481.         ret = regnode(ANY);
  482.         *flagp |= HASWIDTH|SIMPLE;
  483.         break;
  484.     case '[': {
  485.             register int class;
  486.             register int classend;
  487.  
  488.             if (*regparse == '^') {    /* Complement of range. */
  489.                 ret = regnode(ANYBUT);
  490.                 regparse++;
  491.             } else
  492.                 ret = regnode(ANYOF);
  493.             if (*regparse == ']' || *regparse == '-')
  494.                 regc(*regparse++);
  495.             while (*regparse != '\0' && *regparse != ']') {
  496.                 if (*regparse == '-') {
  497.                     regparse++;
  498.                     if (*regparse == ']' || *regparse == '\0')
  499.                         regc('-');
  500.                     else {
  501.                         class = UCHARAT(regparse-2)+1;
  502.                         classend = UCHARAT(regparse);
  503.                         if (class > classend+1)
  504.                             FAIL("invalid [] range");
  505.                         for (; class <= classend; class++)
  506.                             regc(class);
  507.                         regparse++;
  508.                     }
  509.                 } else
  510.                     regc(*regparse++);
  511.             }
  512.             regc('\0');
  513.             if (*regparse != ']')
  514.                 FAIL("unmatched []");
  515.             regparse++;
  516.             *flagp |= HASWIDTH|SIMPLE;
  517.         }
  518.         break;
  519.     case '(':
  520.         ret = reg(1, &flags);
  521.         if (ret == NULL)
  522.             return(NULL);
  523.         *flagp |= flags&(HASWIDTH|SPSTART);
  524.         break;
  525.     case '\0':
  526.     case '|':
  527.     case ')':
  528.         FAIL("internal urp");    /* Supposed to be caught earlier. */
  529.         break;
  530.     case '?':
  531.     case '+':
  532.     case '*':
  533.         FAIL("?+* follows nothing");
  534.         break;
  535.     case '\\':
  536.         if (*regparse == '\0')
  537.             FAIL("trailing \\");
  538.         ret = regnode(EXACTLY);
  539.         regc(*regparse++);
  540.         regc('\0');
  541.         *flagp |= HASWIDTH|SIMPLE;
  542.         break;
  543.     default: {
  544.             register int len;
  545.             register char ender;
  546.  
  547.             regparse--;
  548.             len = strcspn(regparse, META);
  549.             if (len <= 0)
  550.                 FAIL("internal disaster");
  551.             ender = *(regparse+len);
  552.             if (len > 1 && ISMULT(ender))
  553.                 len--;        /* Back off clear of ?+* operand. */
  554.             *flagp |= HASWIDTH;
  555.             if (len == 1)
  556.                 *flagp |= SIMPLE;
  557.             ret = regnode(EXACTLY);
  558.             while (len > 0) {
  559.                 regc(*regparse++);
  560.                 len--;
  561.             }
  562.             regc('\0');
  563.         }
  564.         break;
  565.     }
  566.  
  567.     return(ret);
  568. }
  569.  
  570. /*
  571.  - regnode - emit a node
  572.  */
  573. static char *            /* Location. */
  574. regnode(op)
  575. char op;
  576. {
  577.     register char *ret;
  578.     register char *ptr;
  579.  
  580.     ret = regcode;
  581.     if (ret == ®dummy) {
  582.         regsize += 3;
  583.         return(ret);
  584.     }
  585.  
  586.     ptr = ret;
  587.     *ptr++ = op;
  588.     *ptr++ = '\0';        /* Null "next" pointer. */
  589.     *ptr++ = '\0';
  590.     regcode = ptr;
  591.  
  592.     return(ret);
  593. }
  594.  
  595. /*
  596.  - regc - emit (if appropriate) a byte of code
  597.  */
  598. static void
  599. regc(b)
  600. char b;
  601. {
  602.     if (regcode != ®dummy)
  603.         *regcode++ = b;
  604.     else
  605.         regsize++;
  606. }
  607.  
  608. /*
  609.  - reginsert - insert an operator in front of already-emitted operand
  610.  *
  611.  * Means relocating the operand.
  612.  */
  613. static void
  614. reginsert(op, opnd)
  615. char op;
  616. char *opnd;
  617. {
  618.     register char *src;
  619.     register char *dst;
  620.     register char *place;
  621.  
  622.     if (regcode == ®dummy) {
  623.         regsize += 3;
  624.         return;
  625.     }
  626.  
  627.     src = regcode;
  628.     regcode += 3;
  629.     dst = regcode;
  630.     while (src > opnd)
  631.         *--dst = *--src;
  632.  
  633.     place = opnd;        /* Op node, where operand used to be. */
  634.     *place++ = op;
  635.     *place++ = '\0';
  636.     *place++ = '\0';
  637. }
  638.  
  639. /*
  640.  - regtail - set the next-pointer at the end of a node chain
  641.  */
  642. static void
  643. regtail(p, val)
  644. char *p;
  645. char *val;
  646. {
  647.     register char *scan;
  648.     register char *temp;
  649.     register int offset;
  650.  
  651.     if (p == ®dummy)
  652.         return;
  653.  
  654.     /* Find last node. */
  655.     scan = p;
  656.     for (;;) {
  657.         temp = regnext(scan);
  658.         if (temp == NULL)
  659.             break;
  660.         scan = temp;
  661.     }
  662.  
  663.     if (OP(scan) == BACK)
  664.         offset = scan - val;
  665.     else
  666.         offset = val - scan;
  667.     *(scan+1) = (offset>>8)&0377;
  668.     *(scan+2) = offset&0377;
  669. }
  670.  
  671. /*
  672.  - regoptail - regtail on operand of first argument; nop if operandless
  673.  */
  674. static void
  675. regoptail(p, val)
  676. char *p;
  677. char *val;
  678. {
  679.     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  680.     if (p == NULL || p == ®dummy || OP(p) != BRANCH)
  681.         return;
  682.     regtail(OPERAND(p), val);
  683. }
  684.  
  685. /*
  686.  * regexec and friends
  687.  */
  688.  
  689. /*
  690.  * Global work variables for regexec().
  691.  */
  692. static char *reginput;        /* String-input pointer. */
  693. static char *regbol;        /* Beginning of input, for ^ check. */
  694. static char **regstartp;    /* Pointer to startp array. */
  695. static char **regendp;        /* Ditto for endp. */
  696.  
  697. /*
  698.  * Forwards.
  699.  */
  700. STATIC int regtry();
  701. STATIC int regmatch();
  702. STATIC int regrepeat();
  703.  
  704. #ifdef DEBUG
  705. int regnarrate = 0;
  706. void regdump();
  707. STATIC char *regprop();
  708. #endif
  709.  
  710. /*
  711.  - regexec - match a regexp against a string
  712.  */
  713. int
  714. regexec(prog, string)
  715. register regexp *prog;
  716. register char *string;
  717. {
  718.     register char *s;
  719.  
  720.     /* Be paranoid... */
  721.     if (prog == NULL || string == NULL) {
  722.         regerror("NULL parameter");
  723.         return(0);
  724.     }
  725.  
  726.     /* Check validity of program. */
  727.     if (UCHARAT(prog->program) != MAGIC) {
  728.         regerror("corrupted program");
  729.         return(0);
  730.     }
  731.  
  732.     /* If there is a "must appear" string, look for it. */
  733.     if (prog->regmust != NULL) {
  734.         s = string;
  735.         while ((s = (char *)strchr(s, prog->regmust[0])) != NULL) {
  736.             if (strncmp(s, prog->regmust, prog->regmlen) == 0)
  737.                 break;    /* Found it. */
  738.             s++;
  739.         }
  740.         if (s == NULL)    /* Not present. */
  741.             return(0);
  742.     }
  743.  
  744.     /* Mark beginning of line for ^ . */
  745.     regbol = string;
  746.  
  747.     /* Simplest case:  anchored match need be tried only once. */
  748.     if (prog->reganch)
  749.         return(regtry(prog, string));
  750.  
  751.     /* Messy cases:  unanchored match. */
  752.     s = string;
  753.     if (prog->regstart != '\0')
  754.         /* We know what char it must start with. */
  755.         while ((s = (char *)strchr(s, prog->regstart)) != NULL) {
  756.             if (regtry(prog, s))
  757.                 return(1);
  758.             s++;
  759.         }
  760.     else
  761.         /* We don't -- general case. */
  762.         do {
  763.             if (regtry(prog, s))
  764.                 return(1);
  765.         } while (*s++ != '\0');
  766.  
  767.     /* Failure. */
  768.     return(0);
  769. }
  770.  
  771. /*
  772.  - regtry - try match at specific point
  773.  */
  774. static int            /* 0 failure, 1 success */
  775. regtry(prog, string)
  776. regexp *prog;
  777. char *string;
  778. {
  779.     register int i;
  780.     register char **sp;
  781.     register char **ep;
  782.  
  783.     reginput = string;
  784.     regstartp = prog->startp;
  785.     regendp = prog->endp;
  786.  
  787.     sp = prog->startp;
  788.     ep = prog->endp;
  789.     for (i = NSUBEXP; i > 0; i--) {
  790.         *sp++ = NULL;
  791.         *ep++ = NULL;
  792.     }
  793.     if (regmatch(prog->program + 1)) {
  794.         prog->startp[0] = string;
  795.         prog->endp[0] = reginput;
  796.         return(1);
  797.     } else
  798.         return(0);
  799. }
  800.  
  801. /*
  802.  - regmatch - main matching routine
  803.  *
  804.  * Conceptually the strategy is simple:  check to see whether the current
  805.  * node matches, call self recursively to see whether the rest matches,
  806.  * and then act accordingly.  In practice we make some effort to avoid
  807.  * recursion, in particular by going through "ordinary" nodes (that don't
  808.  * need to know whether the rest of the match failed) by a loop instead of
  809.  * by recursion.
  810.  */
  811. static int            /* 0 failure, 1 success */
  812. regmatch(prog)
  813. char *prog;
  814. {
  815.     register char *scan;    /* Current node. */
  816.     char *next;        /* Next node. */
  817.  
  818.     scan = prog;
  819. #ifdef DEBUG
  820.     if (scan != NULL && regnarrate)
  821.         fprintf(stderr, "%s(\n", regprop(scan));
  822. #endif
  823.     while (scan != NULL) {
  824. #ifdef DEBUG
  825.         if (regnarrate)
  826.             fprintf(stderr, "%s...\n", regprop(scan));
  827. #endif
  828.         next = regnext(scan);
  829.  
  830.         switch (OP(scan)) {
  831.         case BOL:
  832.             if (reginput != regbol)
  833.                 return(0);
  834.             break;
  835.         case EOL:
  836.             if (*reginput != '\0')
  837.                 return(0);
  838.             break;
  839.         case ANY:
  840.             if (*reginput == '\0')
  841.                 return(0);
  842.             reginput++;
  843.             break;
  844.         case EXACTLY: {
  845.                 register int len;
  846.                 register char *opnd;
  847.  
  848.                 opnd = OPERAND(scan);
  849.                 /* Inline the first character, for speed. */
  850.                 if (*opnd != *reginput)
  851.                     return(0);
  852.                 len = strlen(opnd);
  853.                 if (len > 1 && strncmp(opnd, reginput, len) != 0)
  854.                     return(0);
  855.                 reginput += len;
  856.             }
  857.             break;
  858.         case ANYOF:
  859.             if (*reginput == '\0' || (char *)strchr(OPERAND(scan), *reginput) == NULL)
  860.                 return(0);
  861.             reginput++;
  862.             break;
  863.         case ANYBUT:
  864.             if (*reginput == '\0' || (char *)strchr(OPERAND(scan), *reginput) != NULL)
  865.                 return(0);
  866.             reginput++;
  867.             break;
  868.         case NOTHING:
  869.             break;
  870.         case BACK:
  871.             break;
  872.         case OPEN+1:
  873.         case OPEN+2:
  874.         case OPEN+3:
  875.         case OPEN+4:
  876.         case OPEN+5:
  877.         case OPEN+6:
  878.         case OPEN+7:
  879.         case OPEN+8:
  880.         case OPEN+9: {
  881.                 register int no;
  882.                 register char *save;
  883.  
  884.                 no = OP(scan) - OPEN;
  885.                 save = reginput;
  886.  
  887.                 if (regmatch(next)) {
  888.                     /*
  889.                      * Don't set startp if some later
  890.                      * invocation of the same parentheses
  891.                      * already has.
  892.                      */
  893.                     if (regstartp[no] == NULL)
  894.                         regstartp[no] = save;
  895.                     return(1);
  896.                 } else
  897.                     return(0);
  898.             }
  899.             break;
  900.         case CLOSE+1:
  901.         case CLOSE+2:
  902.         case CLOSE+3:
  903.         case CLOSE+4:
  904.         case CLOSE+5:
  905.         case CLOSE+6:
  906.         case CLOSE+7:
  907.         case CLOSE+8:
  908.         case CLOSE+9: {
  909.                 register int no;
  910.                 register char *save;
  911.  
  912.                 no = OP(scan) - CLOSE;
  913.                 save = reginput;
  914.  
  915.                 if (regmatch(next)) {
  916.                     /*
  917.                      * Don't set endp if some later
  918.                      * invocation of the same parentheses
  919.                      * already has.
  920.                      */
  921.                     if (regendp[no] == NULL)
  922.                         regendp[no] = save;
  923.                     return(1);
  924.                 } else
  925.                     return(0);
  926.             }
  927.             break;
  928.         case BRANCH: {
  929.                 register char *save;
  930.  
  931.                 if (OP(next) != BRANCH)        /* No choice. */
  932.                     next = OPERAND(scan);    /* Avoid recursion. */
  933.                 else {
  934.                     do {
  935.                         save = reginput;
  936.                         if (regmatch(OPERAND(scan)))
  937.                             return(1);
  938.                         reginput = save;
  939.                         scan = regnext(scan);
  940.                     } while (scan != NULL && OP(scan) == BRANCH);
  941.                     return(0);
  942.                     /* NOTREACHED */
  943.                 }
  944.             }
  945.             break;
  946.         case STAR:
  947.         case PLUS: {
  948.                 register char nextch;
  949.                 register int no;
  950.                 register char *save;
  951.                 register int min;
  952.  
  953.                 /*
  954.                  * Lookahead to avoid useless match attempts
  955.                  * when we know what character comes next.
  956.                  */
  957.                 nextch = '\0';
  958.                 if (OP(next) == EXACTLY)
  959.                     nextch = *OPERAND(next);
  960.                 min = (OP(scan) == STAR) ? 0 : 1;
  961.                 save = reginput;
  962.                 no = regrepeat(OPERAND(scan));
  963.                 while (no >= min) {
  964.                     /* If it could work, try it. */
  965.                     if (nextch == '\0' || *reginput == nextch)
  966.                         if (regmatch(next))
  967.                             return(1);
  968.                     /* Couldn't or didn't -- back up. */
  969.                     no--;
  970.                     reginput = save + no;
  971.                 }
  972.                 return(0);
  973.             }
  974.             break;
  975.         case END:
  976.             return(1);    /* Success! */
  977.             break;
  978.         default:
  979.             regerror("memory corruption");
  980.             return(0);
  981.             break;
  982.         }
  983.  
  984.         scan = next;
  985.     }
  986.  
  987.     /*
  988.      * We get here only if there's trouble -- normally "case END" is
  989.      * the terminating point.
  990.      */
  991.     regerror("corrupted pointers");
  992.     return(0);
  993. }
  994.  
  995. /*
  996.  - regrepeat - repeatedly match something simple, report how many
  997.  */
  998. static int
  999. regrepeat(p)
  1000. char *p;
  1001. {
  1002.     register int count = 0;
  1003.     char *scan;
  1004.     char *opnd;
  1005.     char *cp;
  1006.  
  1007.     scan = reginput;
  1008.     opnd = OPERAND(p);
  1009.     switch (OP(p)) {
  1010.     case ANY:
  1011.         count = strlen(scan);
  1012.         scan += count;
  1013.         break;
  1014.     case EXACTLY:
  1015.         while (*opnd == *scan) {
  1016.             count++;
  1017.             scan++;
  1018.         }
  1019.         break;
  1020.     case ANYOF:
  1021.         cp = (char *)strchr(opnd, *scan);
  1022.         while (*scan != '\0' && cp != NULL) {
  1023.             count++;
  1024.             scan++;
  1025.             cp = (char *)strchr(opnd, *scan);
  1026.         }
  1027.         break;
  1028.     case ANYBUT:
  1029.         while (*scan != '\0' && (char *)strchr(opnd, *scan) == NULL) {
  1030.             count++;
  1031.             scan++;
  1032.         }
  1033.         break;
  1034.     default:        /* Oh dear.  Called inappropriately. */
  1035.         regerror("internal foulup");
  1036.         count = 0;    /* Best compromise. */
  1037.         break;
  1038.     }
  1039.     reginput = scan;
  1040.  
  1041.     return(count);
  1042. }
  1043.  
  1044. /*
  1045.  - regnext - dig the "next" pointer out of a node
  1046.  */
  1047. static char *
  1048. regnext(p)
  1049. register char *p;
  1050. {
  1051.     register int offset;
  1052.  
  1053.     if (p == ®dummy)
  1054.         return(NULL);
  1055.  
  1056.     offset = NEXT(p);
  1057.     if (offset == 0)
  1058.         return(NULL);
  1059.  
  1060.     if (OP(p) == BACK)
  1061.         return(p-offset);
  1062.     else
  1063.         return(p+offset);
  1064. }
  1065.  
  1066. #ifdef DEBUG
  1067.  
  1068. STATIC char *regprop();
  1069.  
  1070. /*
  1071.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  1072.  */
  1073. void
  1074. regdump(r)
  1075. regexp *r;
  1076. {
  1077.     register char *s;
  1078.     register char op = EXACTLY;    /* Arbitrary non-END op. */
  1079.     register char *next;
  1080.  
  1081.  
  1082.     s = r->program + 1;
  1083.     while (op != END) {    /* While that wasn't END last time... */
  1084.         op = OP(s);
  1085.         printf("%2d%s", s-r->program, regprop(s));    /* Where, what. */
  1086.         next = regnext(s);
  1087.         if (next == NULL)        /* Next ptr. */
  1088.             printf("(0)");
  1089.         else 
  1090.             printf("(%d)", (s-r->program)+(next-s));
  1091.         s += 3;
  1092.         if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1093.             /* Literal string, where present. */
  1094.             while (*s != '\0') {
  1095.                 putchar(*s);
  1096.                 s++;
  1097.             }
  1098.             s++;
  1099.         }
  1100.         putchar('\n');
  1101.     }
  1102.  
  1103.     /* Header fields of interest. */
  1104.     if (r->regstart != '\0')
  1105.         printf("start `%c' ", r->regstart);
  1106.     if (r->reganch)
  1107.         printf("anchored ");
  1108.     if (r->regmust != NULL)
  1109.         printf("must have \"%s\"", r->regmust);
  1110.     printf("\n");
  1111. }
  1112.  
  1113. /*
  1114.  - regprop - printable representation of opcode
  1115.  */
  1116. static char *
  1117. regprop(op)
  1118. char *op;
  1119. {
  1120.     register char *p;
  1121.     static char buf[50];
  1122.  
  1123.     (void) strcpy(buf, ":");
  1124.  
  1125.     switch (OP(op)) {
  1126.     case BOL:
  1127.         p = "BOL";
  1128.         break;
  1129.     case EOL:
  1130.         p = "EOL";
  1131.         break;
  1132.     case ANY:
  1133.         p = "ANY";
  1134.         break;
  1135.     case ANYOF:
  1136.         p = "ANYOF";
  1137.         break;
  1138.     case ANYBUT:
  1139.         p = "ANYBUT";
  1140.         break;
  1141.     case BRANCH:
  1142.         p = "BRANCH";
  1143.         break;
  1144.     case EXACTLY:
  1145.         p = "EXACTLY";
  1146.         break;
  1147.     case NOTHING:
  1148.         p = "NOTHING";
  1149.         break;
  1150.     case BACK:
  1151.         p = "BACK";
  1152.         break;
  1153.     case END:
  1154.         p = "END";
  1155.         break;
  1156.     case OPEN+1:
  1157.     case OPEN+2:
  1158.     case OPEN+3:
  1159.     case OPEN+4:
  1160.     case OPEN+5:
  1161.     case OPEN+6:
  1162.     case OPEN+7:
  1163.     case OPEN+8:
  1164.     case OPEN+9:
  1165.         sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
  1166.         p = NULL;
  1167.         break;
  1168.     case CLOSE+1:
  1169.     case CLOSE+2:
  1170.     case CLOSE+3:
  1171.     case CLOSE+4:
  1172.     case CLOSE+5:
  1173.     case CLOSE+6:
  1174.     case CLOSE+7:
  1175.     case CLOSE+8:
  1176.     case CLOSE+9:
  1177.         sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
  1178.         p = NULL;
  1179.         break;
  1180.     case STAR:
  1181.         p = "STAR";
  1182.         break;
  1183.     case PLUS:
  1184.         p = "PLUS";
  1185.         break;
  1186.     default:
  1187.         regerror("corrupted opcode");
  1188.         break;
  1189.     }
  1190.     if (p != NULL)
  1191.         (void) strcat(buf, p);
  1192.     return(buf);
  1193. }
  1194. #endif
  1195.  
  1196. /*
  1197.  * The following is provided for those people who do not have strcspn() in
  1198.  * their C libraries.  They should get off their butts and do something
  1199.  * about it; at least one public-domain implementation of those (highly
  1200.  * useful) string routines has been published on Usenet.
  1201.  */
  1202. #ifdef STRCSPN
  1203. /*
  1204.  * strcspn - find length of initial segment of s1 consisting entirely
  1205.  * of characters not from s2
  1206.  */
  1207.  
  1208. static int
  1209. strcspn(s1, s2)
  1210. char *s1;
  1211. char *s2;
  1212. {
  1213.     register char *scan1;
  1214.     register char *scan2;
  1215.     register int count;
  1216.  
  1217.     count = 0;
  1218.     for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1219.         for (scan2 = s2; *scan2 != '\0';)    /* ++ moved down. */
  1220.             if (*scan1 == *scan2++)
  1221.                 return(count);
  1222.         count++;
  1223.     }
  1224.     return(count);
  1225. }
  1226. #endif
  1227.